# -*- coding:utf-8 -*-
# @Time    : 2021/05/21 17:16
# @Author  : wangleip
# @Remark  : 百度地图爬虫类
# @Software: PyCharm

import config
import requests
import json


class BaiduMapSpider:
    '百度地图爬虫类'

    def __init__(self):
        # 百度地图AK
        self.baidu_ak = config.BAIDU_AK
        # 默认的http请求头
        self.default_headers = {"User-Agent": config.DEFAULT_REQUEST_HEADER_USER_AGENT}

    def get_data(self, region, tag):
        """
        调用百度地图接口，爬去数据
        :param region: 城市名称
        :param tag: 数据标签
        :return:
        """
        try:
            # http://api.map.baidu.com/place/v2/search?query=ATM机&tag=银行&region=北京&output=json&ak=您的ak
            par = {'query': tag, 'tag': tag, 'region': region, 'output': 'json', 'ak': self.baidu_ak}
            url = 'http://api.map.baidu.com/place/v2/search'
            res = requests.get(url, params=par, headers=self.default_headers)
            if res.status_code == 200:
                # 将返回数据转化成JSON
                json_data = json.loads(res.content.decode())
                # print(json_data)
                if json_data['message'] == 'ok':
                    return json_data['results']
                else:
                    return None
        except Exception as err:
            print(err)

    def processing_data(self, data):
        """
        处理爬去的数据
        :param data: 爬取结果数据
        """
        for item in data:
            print(item)

    def run(self, region, tag):
        print('------------%s %s -------------' % (region, tag))
        return self.get_data(region, tag)
        # if result is not None:
        #     self.processing_data(result)
